<template>
  <div class="watermark">
    <h2>图片水印</h2>
    <el-card class="watermark-card">
      <el-upload
        class="upload-demo"
        drag
        action="/api/image/watermark"
        :on-success="handleSuccess"
        :on-error="handleError"
        :before-upload="beforeUpload"
        :data="watermarkData"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽图片到此处或 <em>点击上传</em>
        </div>
      </el-upload>
      
      <div class="watermark-options">
        <el-form :model="watermarkData" label-width="100px">
          <el-form-item label="水印文字">
            <el-input v-model="watermarkData.text" placeholder="请输入水印文字" />
          </el-form-item>
          
          <el-form-item label="字体大小">
            <el-input-number v-model="watermarkData.fontSize" :min="12" :max="100" />
          </el-form-item>
          
          <el-form-item label="透明度">
            <el-slider
              v-model="watermarkData.opacity"
              :min="0"
              :max="1"
              :step="0.1"
              show-input
            />
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-dialog v-model="showPreview" title="水印预览">
      <div class="preview-container">
        <div class="preview-item">
          <h4>原图</h4>
          <img :src="originalImage" alt="原图" v-if="originalImage" />
        </div>
        <div class="preview-item">
          <h4>添加水印后</h4>
          <img :src="watermarkedImage" alt="水印后" v-if="watermarkedImage" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'

const showPreview = ref(false)
const originalImage = ref('')
const watermarkedImage = ref('')

const watermarkData = reactive({
  text: '版权所有',
  fontSize: 48,
  opacity: 0.5
})

const beforeUpload = (file: File) => {
  if (!file.type.includes('image/')) {
    ElMessage.error('请上传图片文件')
    return false
  }
  const reader = new FileReader()
  reader.onload = (e) => {
    originalImage.value = e.target?.result as string
  }
  reader.readAsDataURL(file)
  return true
}

const handleSuccess = (response: any) => {
  ElMessage.success('水印添加成功')
  watermarkedImage.value = `/api/image/download/${response.filename}`
  showPreview.value = true
}

const handleError = () => {
  ElMessage.error('水印添加失败')
}
</script>

<style scoped>
.watermark {
  padding: 2rem;
}

.watermark-card {
  max-width: 600px;
  margin: 2rem auto;
}

.watermark-options {
  margin-top: 2rem;
  padding: 0 2rem;
}

.preview-container {
  display: flex;
  gap: 2rem;
  justify-content: center;
}

.preview-item {
  text-align: center;
}

.preview-item img {
  max-width: 300px;
  max-height: 300px;
  object-fit: contain;
}

.preview-item h4 {
  margin-bottom: 1rem;
}
</style> 